/**
 * 上下文菜单选项类型
 */
const ContextMenuOptionType = {
    FILE: 'file',
    FOLDER: 'folder',
    PROBLEMS: 'problems',
    TERMINAL: 'terminal',
    URL: 'url',
    GIT: 'git',
    NO_RESULTS: 'noResults'
};

/**
 * 创建上下文菜单DOM元素
 * @param {function} onSelect - 选择选项时的回调函数
 * @param {string} searchQuery - 搜索查询
 * @param {function} onMouseDown - 鼠标按下时的回调函数
 * @param {number} selectedIndex - 当前选择的索引
 * @param {function} setSelectedIndex - 设置选择索引的回调函数
 * @param {Array} queryItems - 查询选项列表
 * @param {Array} dynamicSearchResults - 动态搜索结果
 * @param {boolean} isLoading - 是否正在加载
 * @returns {HTMLElement} 上下文菜单DOM元素
 */
function createContextMenu(
    onSelect,
    searchQuery,
    onMouseDown,
    selectedIndex,
    setSelectedIndex,
    queryItems,
    dynamicSearchResults = [],
    isLoading = false
) {
    const menuContainer = document.createElement('div');
    menuContainer.style.position = 'absolute';
    menuContainer.style.bottom = 'calc(100% - 10px)';
    menuContainer.style.left = '15px';
    menuContainer.style.right = '15px';
    menuContainer.style.overflowX = 'hidden';
    menuContainer.addEventListener('mousedown', onMouseDown);

    const menuContent = document.createElement('div');
    menuContent.style.backgroundColor = 'var(--vscode-dropdown-background)';
    menuContent.style.border = '1px solid var(--vscode-editorGroup-border)';
    menuContent.style.borderRadius = '3px';
    menuContent.style.boxShadow = '0 4px 10px rgba(0, 0, 0, 0.25)';
    menuContent.style.zIndex = '1000';
    menuContent.style.display = 'flex';
    menuContent.style.flexDirection = 'column';
    menuContent.style.maxHeight = '200px';
    menuContent.style.overflowY = 'auto';

    // 显示加载指示器
    if (isLoading && searchQuery) {
        const loadingItem = document.createElement('div');
        loadingItem.style.padding = '8px 12px';
        loadingItem.style.display = 'flex';
        loadingItem.style.alignItems = 'center';
        loadingItem.style.gap = '8px';
        loadingItem.style.opacity = '0.7';
        
        const loadingIcon = document.createElement('span');
        loadingIcon.className = 'codicon codicon-loading codicon-modifier-spin';
        loadingIcon.style.fontSize = '14px';
        
        const loadingText = document.createElement('span');
        loadingText.textContent = '搜索中...';
        
        loadingItem.appendChild(loadingIcon);
        loadingItem.appendChild(loadingText);
        menuContent.appendChild(loadingItem);
    }

    // 获取过滤后的选项
    const filteredOptions = getContextMenuOptions(searchQuery, null, queryItems, dynamicSearchResults);

    // 渲染选项
    filteredOptions.forEach((option, index) => {
        const optionElement = document.createElement('div');
        
        // 设置是否可选择
        const isSelectable = isOptionSelectable(option);
        
        // 设置选项样式
        optionElement.style.padding = '8px 12px';
        optionElement.style.cursor = isSelectable ? 'pointer' : 'default';
        optionElement.style.color = (index === selectedIndex && isSelectable) 
            ? 'var(--vscode-quickInputList-focusForeground)' 
            : '';
        optionElement.style.borderBottom = '1px solid var(--vscode-editorGroup-border)';
        optionElement.style.display = 'flex';
        optionElement.style.alignItems = 'center';
        optionElement.style.justifyContent = 'space-between';
        optionElement.style.backgroundColor = (index === selectedIndex && isSelectable)
            ? 'var(--vscode-quickInputList-focusBackground)'
            : '';
        
        // 选项点击事件
        if (isSelectable) {
            optionElement.addEventListener('click', () => onSelect(option.type, option.value));
            optionElement.addEventListener('mouseenter', () => setSelectedIndex(index));
        }
        
        // 添加选项内容
        const contentContainer = document.createElement('div');
        contentContainer.style.display = 'flex';
        contentContainer.style.alignItems = 'center';
        contentContainer.style.flex = '1';
        contentContainer.style.minWidth = '0';
        contentContainer.style.overflow = 'hidden';
        
        // 添加图标
        const icon = document.createElement('span');
        icon.className = `codicon codicon-${getIconForOption(option)}`;
        icon.style.marginRight = '8px';
        icon.style.flexShrink = '0';
        icon.style.fontSize = '14px';
        contentContainer.appendChild(icon);
        
        // 添加内容
        const content = renderOptionContent(option);
        contentContainer.appendChild(content);
        optionElement.appendChild(contentContainer);
        
        // 添加子菜单指示器
        if ((option.type === ContextMenuOptionType.FILE || 
             option.type === ContextMenuOptionType.FOLDER || 
             option.type === ContextMenuOptionType.GIT) && !option.value) {
            const chevron = document.createElement('span');
            chevron.className = 'codicon codicon-chevron-right';
            chevron.style.fontSize = '14px';
            chevron.style.flexShrink = '0';
            chevron.style.marginLeft = '8px';
            optionElement.appendChild(chevron);
        }
        
        menuContent.appendChild(optionElement);
    });

    menuContainer.appendChild(menuContent);
    return menuContainer;
}

/**
 * 判断选项是否可选
 * @param {Object} option - 选项对象
 * @returns {boolean} 是否可选
 */
function isOptionSelectable(option) {
    return option.type !== ContextMenuOptionType.NO_RESULTS && 
           option.type !== ContextMenuOptionType.URL;
}

/**
 * 获取选项的图标
 * @param {Object} option - 选项对象
 * @returns {string} 图标名称
 */
function getIconForOption(option) {
    switch (option.type) {
        case ContextMenuOptionType.FILE:
            return 'file';
        case ContextMenuOptionType.FOLDER:
            return 'folder';
        case ContextMenuOptionType.PROBLEMS:
            return 'warning';
        case ContextMenuOptionType.TERMINAL:
            return 'terminal';
        case ContextMenuOptionType.URL:
            return 'link';
        case ContextMenuOptionType.GIT:
            return 'git-commit';
        case ContextMenuOptionType.NO_RESULTS:
            return 'info';
        default:
            return 'file';
    }
}

/**
 * 渲染选项内容
 * @param {Object} option - 选项对象
 * @returns {HTMLElement} 内容DOM元素
 */
function renderOptionContent(option) {
    const container = document.createElement('div');
    
    switch (option.type) {
        case ContextMenuOptionType.PROBLEMS:
            container.textContent = '工作区问题';
            break;
        case ContextMenuOptionType.TERMINAL:
            container.textContent = '终端输出';
            break;
        case ContextMenuOptionType.URL:
            container.textContent = '粘贴URL以获取内容';
            break;
        case ContextMenuOptionType.NO_RESULTS:
            container.textContent = '未找到结果';
            break;
        case ContextMenuOptionType.GIT:
            if (option.value) {
                const container = document.createElement('div');
                container.style.display = 'flex';
                container.style.flexDirection = 'column';
                container.style.gap = '0';
                
                const label = document.createElement('span');
                label.style.lineHeight = '1.2';
                label.textContent = option.label;
                container.appendChild(label);
                
                const description = document.createElement('span');
                description.style.fontSize = '0.85em';
                description.style.opacity = '0.7';
                description.style.whiteSpace = 'nowrap';
                description.style.overflow = 'hidden';
                description.style.textOverflow = 'ellipsis';
                description.style.lineHeight = '1.2';
                description.textContent = option.description;
                container.appendChild(description);
                
                return container;
            } else {
                container.textContent = 'Git提交';
            }
            break;
        case ContextMenuOptionType.FILE:
        case ContextMenuOptionType.FOLDER:
            if (option.value) {
                // 显示路径
                const pathPrefix = document.createElement('span');
                pathPrefix.textContent = '/';
                container.appendChild(pathPrefix);
                
                // 显示隐藏文件的点号
                if (option.value?.startsWith('/.')) {
                    const dot = document.createElement('span');
                    dot.textContent = '.';
                    container.appendChild(dot);
                }
                
                // 显示路径其余部分
                const pathContent = document.createElement('span');
                pathContent.style.whiteSpace = 'nowrap';
                pathContent.style.overflow = 'hidden';
                pathContent.style.textOverflow = 'ellipsis';
                pathContent.style.direction = 'rtl';
                pathContent.style.textAlign = 'left';
                
                const cleanPath = option.value || '';
                pathContent.textContent = cleanPath.replace(/^\//, '') + '\u200E'; // 添加左至右标记
                container.appendChild(pathContent);
            } else {
                container.textContent = `添加${option.type === ContextMenuOptionType.FILE ? '文件' : '文件夹'}`;
            }
            break;
        default:
            container.textContent = option.label || option.value || '';
    }
    
    return container;
}

/**
 * 获取上下文菜单选项
 * @param {string} query - 查询字符串
 * @param {string} selectedType - 当前选择的类型
 * @param {Array} queryItems - 查询项数组
 * @param {Array} dynamicSearchResults - 动态搜索结果
 * @returns {Array} 过滤后的选项数组
 */
function getContextMenuOptions(query, selectedType, queryItems, dynamicSearchResults = []) {
    const workingChanges = {
        type: ContextMenuOptionType.GIT,
        value: 'git-changes',
        label: '工作区变更',
        description: '当前未提交的变更'
    };

    // 如果没有查询，返回基本选项
    if (query === '') {
        if (selectedType === ContextMenuOptionType.FILE) {
            const files = queryItems
                .filter(item => item.type === ContextMenuOptionType.FILE)
                .map(item => ({
                    type: item.type,
                    value: item.value
                }));
            return files.length > 0 ? files : [{ type: ContextMenuOptionType.NO_RESULTS }];
        }

        if (selectedType === ContextMenuOptionType.FOLDER) {
            const folders = queryItems
                .filter(item => item.type === ContextMenuOptionType.FOLDER)
                .map(item => ({
                    type: ContextMenuOptionType.FOLDER,
                    value: item.value
                }));
            return folders.length > 0 ? folders : [{ type: ContextMenuOptionType.NO_RESULTS }];
        }

        if (selectedType === ContextMenuOptionType.GIT) {
            const commits = queryItems.filter(item => item.type === ContextMenuOptionType.GIT);
            return commits.length > 0 ? [workingChanges, ...commits] : [workingChanges];
        }

        return [
            { type: ContextMenuOptionType.URL },
            { type: ContextMenuOptionType.PROBLEMS },
            { type: ContextMenuOptionType.TERMINAL },
            { type: ContextMenuOptionType.GIT },
            { type: ContextMenuOptionType.FOLDER },
            { type: ContextMenuOptionType.FILE }
        ];
    }

    // 处理查询
    const lowerQuery = query.toLowerCase();
    const suggestions = [];

    // 检查顶级选项匹配
    if ('git'.startsWith(lowerQuery)) {
        suggestions.push({
            type: ContextMenuOptionType.GIT,
            label: 'Git提交',
            description: '搜索仓库历史'
        });
    } else if ('git-changes'.startsWith(lowerQuery)) {
        suggestions.push(workingChanges);
    }
    
    if ('problems'.startsWith(lowerQuery)) {
        suggestions.push({ type: ContextMenuOptionType.PROBLEMS });
    }
    
    if ('terminal'.startsWith(lowerQuery)) {
        suggestions.push({ type: ContextMenuOptionType.TERMINAL });
    }
    
    if (query.startsWith('http')) {
        suggestions.push({ type: ContextMenuOptionType.URL, value: query });
    }

    // 添加精确的SHA匹配
    if (/^[a-f0-9]{7,40}$/i.test(lowerQuery)) {
        const exactMatches = queryItems.filter(
            item => item.type === ContextMenuOptionType.GIT && item.value?.toLowerCase() === lowerQuery
        );
        if (exactMatches.length > 0) {
            suggestions.push(...exactMatches);
        } else {
            suggestions.push({
                type: ContextMenuOptionType.GIT,
                value: lowerQuery,
                label: `提交 ${lowerQuery}`,
                description: 'Git提交哈希'
            });
        }
    }

    // 转换动态搜索结果为菜单项
    const searchResultItems = dynamicSearchResults.map(result => {
        const formattedPath = result.path.startsWith('/') ? result.path : `/${result.path}`;
        return {
            type: result.type === 'folder' ? ContextMenuOptionType.FOLDER : ContextMenuOptionType.FILE,
            value: formattedPath,
            label: result.label || path.basename(result.path),
            description: formattedPath
        };
    });

    // 如果有动态搜索结果，优先显示
    if (dynamicSearchResults.length > 0) {
        const allItems = [...suggestions, ...searchResultItems];
        return allItems.length > 0 ? allItems : [{ type: ContextMenuOptionType.NO_RESULTS }];
    }

    // 简单的模糊匹配
    const matchingItems = fuzzySearch(queryItems, query);

    // 整合所有结果
    if (suggestions.length > 0 || matchingItems.length > 0) {
        const allItems = [...suggestions, ...matchingItems];
        
        // 去重
        const seen = new Set();
        const deduped = allItems.filter(item => {
            const key = `${item.type}-${item.value || ''}`;
            if (seen.has(key)) return false;
            seen.add(key);
            return true;
        });
        
        return deduped.length > 0 ? deduped : [{ type: ContextMenuOptionType.NO_RESULTS }];
    }

    return [{ type: ContextMenuOptionType.NO_RESULTS }];
}

/**
 * 简单的模糊搜索实现
 * @param {Array} items - 要搜索的项
 * @param {string} query - 查询字符串
 * @returns {Array} 匹配的项
 */
function fuzzySearch(items, query) {
    if (!query) return [];
    
    const lowerQuery = query.toLowerCase();
    return items.filter(item => {
        const searchStr = [item.value, item.label, item.description]
            .filter(Boolean)
            .join(' ')
            .toLowerCase();
        return searchStr.includes(lowerQuery);
    });
}

/**
 * 判断是否应该显示上下文菜单
 * @param {string} text - 输入文本
 * @param {number} position - 光标位置
 * @returns {boolean} 是否应显示上下文菜单
 */
function shouldShowContextMenu(text, position) {
    if (!text) return false;
    
    const beforeCursor = text.slice(0, position);
    const atIndex = beforeCursor.lastIndexOf('@');
    
    if (atIndex === -1) return false;
    
    const textAfterAt = beforeCursor.slice(atIndex + 1);
    
    // 检查@后面是否有空白字符
    if (/\s/.test(textAfterAt)) return false;
    
    return true;
}

/**
 * 插入@提及
 * @param {string} text - 当前文本
 * @param {number} position - 光标位置
 * @param {string} value - 要插入的值
 * @returns {Object} 新的文本和@符号位置
 */
function insertMention(text, position, value) {
    const beforeCursor = text.slice(0, position);
    const afterCursor = text.slice(position);
    
    // 找到光标前最后一个@符号的位置
    const lastAtIndex = beforeCursor.lastIndexOf('@');
    
    let newValue;
    let mentionIndex;
    
    if (lastAtIndex !== -1) {
        // 如果有@符号，替换它后面的内容
        const beforeMention = text.slice(0, lastAtIndex);
        newValue = beforeMention + '@' + value + ' ' + afterCursor.replace(/^[^\s]*/, '');
        mentionIndex = lastAtIndex;
    } else {
        // 如果没有@符号，在光标位置插入
        newValue = beforeCursor + '@' + value + ' ' + afterCursor;
        mentionIndex = position;
    }
    
    return { newValue, mentionIndex };
}

/**
 * 直接插入@提及
 * @param {string} text - 当前文本
 * @param {number} position - 光标位置
 * @param {string} value - 要插入的值
 * @returns {Object} 新的文本和@符号位置
 */
function insertMentionDirectly(text, position, value) {
    const beforeCursor = text.slice(0, position);
    const afterCursor = text.slice(position);
    const newValue = beforeCursor + '@' + value + ' ' + afterCursor;
    return { newValue, mentionIndex: position };
}

/**
 * 删除@提及
 * @param {string} text - 当前文本
 * @param {number} position - 光标位置
 * @returns {Object} 新的文本和光标位置
 */
function removeMention(text, position) {
    const beforeCursor = text.slice(0, position);
    const afterCursor = text.slice(position);
    
    // 检查是否在提及的结尾
    const match = beforeCursor.match(/@([^\s]+)$/);
    
    if (match) {
        // 如果在提及末尾，删除它
        const newText = text.slice(0, position - match[0].length) + afterCursor;
        return { newText, newPosition: position - match[0].length };
    }
    
    // 如果不在提及末尾，返回原始文本
    return { newText: text, newPosition: position };
}

// 导出函数和常量
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        ContextMenuOptionType,
        createContextMenu,
        shouldShowContextMenu,
        insertMention,
        insertMentionDirectly,
        removeMention
    };
} 